#define _CRT_SECURE_NO_WARNINGS 1

class Solution
{
    vector<vector<bool>> vis;
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int m, n;
public:
    int orangesRotting(vector<vector<int>>& grid)
    {
        int m = grid.size(), n = grid[0].size();
        vis = vector<vector<bool>>(m, vector<bool>(n));
        queue<pair<int, int>> q;
        int ret = 0;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 2) q.push({ i, j });
            }
        }

        while (q.size())
        {
            int sz = q.size();
            while (sz--)
            {
                auto [_x, _y] = q.front();
                q.pop();
                for (int i = 0; i < 4; i++)
                {
                    int x = _x + dx[i];
                    int y = _y + dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] == 1)
                    {
                        q.push({ x, y });
                        grid[x][y] = 2;
                        vis[x][y] = true;
                    }
                }
            }
            ret++;
        }

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 1) return -1;
            }
        }

        return ret == 0 ? 0 : ret - 1;
    }

};